package middleware.llvm.value;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;

/**
 * IR 中的用户，指使用其他 IR 值的指令或表达式
 *
 * @author 杨凯伟
 * @date 2024/10/30
 */
public abstract class User extends Value {
    protected final List<Value> operands = new ArrayList<>();

    public User(IRType type, Value... operands) {
        super(type);
//        int pos = 0;
//        for (var op : operands) {
//            if (op != null) {
//                op.addUse(this, pos);
//            }
//            this.operands.add(op);
//            pos++;
//        }
        IntStream.range(0, operands.length).forEach(i -> {
            Value op = operands[i];
            if (op != null) {
                op.addUse(this, i);
            }
            this.operands.add(op);
        });
    }

    public List<Value> getOperands() {
        return operands;
    }

    public void replaceOperand(int pos, Value newOperand) {
        operands.set(pos, newOperand);
    }

    public void addOperand(Value newOperand) {
        newOperand.addUse(this, operands.size());
        operands.add(newOperand);
    }
}
